//
//  HZRefrashControl.swift
//  weibo002
//
//  Created by 黑眼圈 on 16/4/23.
//  Copyright © 2016年 heiyan. All rights reserved.
//

import UIKit


//定义一个记录刷新控件状态的枚举
enum HZRefrashControlState:String{
    
    case normal = "普通"
    case pulling = "下拉"
    case refrash = "刷新"
}




class HZRefrashControl: UIControl {
    
    
    var tableView:UITableView?
    
    
    //定义一个刷新的状态的属性
    var statePull:HZRefrashControlState? = .normal {
        
        
        didSet{
            
            if statePull == .normal {
                
                textLabel.text = "等待装逼"
                
                //箭头出现
                icon.hidden = false
                
       
                UIView.animateWithDuration(0.25, animations: { () -> Void in
    
                    //箭头恢复原样
                    self.icon.transform = CGAffineTransformIdentity
                })
                

             
                
                //菊花停止旋转并隐藏
                activity.stopAnimating()
                
                
            }else if statePull == .pulling {
                
                textLabel.text = "松手装逼"
                
                //箭头旋转180度
                UIView.animateWithDuration(0.25, animations: { () -> Void in
       
                    self.icon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
        
                
            }else {
                
                textLabel.text = "正在装逼"
                
                //隐藏箭头
                icon.hidden = true
                
                //开启菊花旋转
                activity.startAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.tableView?.contentInset.top += self.bounds.size.height
                })
                
                
                //调用父类的方法
                sendActionsForControlEvents(.TouchUpInside)
                
                
                
            }
            
            
            
        }
    }
    
    //封装一个更新完之后停止的方法
    func stopRef(){
        
   
        //tableView 恢复到初始的位置
        if statePull == .refrash{
            
//            print(self.bounds.size.height)
            
            UIView.animateWithDuration(0.25) { () -> Void in
            
                self.tableView?.contentInset.top -= self.bounds.size.height
            }
        
        }
        
        //恢复普通的状态
        statePull = .normal
        
//        print(self.tableView?.contentInset.top)
     
    }
   
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //设置背景色
//        backgroundColor = UIColor.orangeColor()
        
        setupUI()
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //添加子控件
    private func setupUI(){
        
        addSubview(icon)
        addSubview(textLabel)
        addSubview(activity)
        
        
        //约束
         icon.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        
        textLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerY.equalTo(icon)
            make.leading.equalTo(icon.snp_trailing).offset(10)
        }
        
        activity.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(icon)
        }
        
    }
    
    
    
    
    
    // MARK: -  将要添加到父控件的时候
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
//        print("添加了")
//
        guard let teble = newSuperview where newSuperview!.isKindOfClass(UITableView.self) else{
         
            return
        }

        //获取到父控件
        self.tableView = teble as? UITableView

    
        //KVO监听
       tableView!.addObserver(self, forKeyPath: "contentOffset", options: [ .New], context: nil)
        
        
    }
    
    
    // MARK: -  实现 KVO 方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
//        print(tableView?.contentOffset.y)
    
        let excursion = -tableView!.contentInset.top-self.bounds.size.height


        
        let con = tableView!.contentOffset.y ?? 0
//                print(excursion)
//        
//                print(con)
        
        //如果正在拖拽
        if tableView!.dragging {
            
            //如果下拉刷新的控件全出现了
            if con < excursion && statePull == .normal{
                
                //下拉还没刷新状态
                statePull = .pulling
                
//                print("还没刷新")
                
                
            }else if con >= excursion && statePull == .pulling{
                
                //普通状态
                statePull = .normal
            
              
//                print("等待")
            }

            
        } else{
            //如果结束拖拽了
            //如果下拉刷新的控件全出现了
            if statePull == .pulling {
                
                //变成刷新的状态
                statePull = .refrash
                
//                print("刷新")
            }
            

        }
        
        
        
        
    }
    
    
    // MARK: -  懒加载子控件
    private lazy var icon:UIImageView  = {
        
        let icon = UIImageView()
        
        icon.image = UIImage(named: "tableview_pull_refresh")
        
        return icon
    }()

    
    private lazy var textLabel:UILabel = {
        
        let textLabel = UILabel()
       
        textLabel.font = UIFont.systemFontOfSize(14)
        
        textLabel.text = "等待装逼"
        
        return textLabel
    }()
    
    
    //懒加载菊花
    private lazy var activity:UIActivityIndicatorView = {
        
       let activity = UIActivityIndicatorView()
        
        return activity
    }()
    
    
    
    

}
